<template>
	<rui-pages>
		<view class="xbox">
			<view class="xbox_head">
				<image :src="info.image" mode="widthFix" class="xbox_head_img"></image>

				<view class="xbox_head_info">
					<view class="xbox_head_info_item">
						<view class="xbox_head_info_item_text">
							电量
						</view>
						<view class="xbox_head_info_item_value">
							{{info.quantity || 0}}%
						</view>
					</view>
					<view class="xbox_head_info_item">
						<view class="xbox_head_info_item_text">
							指纹数量
						</view>
						<view class="xbox_head_info_item_value">
							{{product.getFingerprint}}枚
						</view>
					</view>
				</view>
			</view>

			<view class="xbox_fast">
				<view class="xbox_fast_item">
					<view class="xbox_fast_item_box" @click="open">
						<rui-icons icon="open" size="40" color="var(--color)"></rui-icons>
						<view class="xbox_fast_item_box_name">
							蓝牙解锁
						</view>
					</view>
				</view>
				<view class="xbox_fast_item" @click="$rui.route('/pages/product/sbox-g3/enter/enter')">
					<view class="xbox_fast_item_box">
						<rui-icons icon="finger" size="40" color="var(--color)"></rui-icons>
						<view class="xbox_fast_item_box_name">
							添加指纹
						</view>
					</view>
				</view>
			</view>

			<view class="xbox_controller">
				<view class="xbox_controller_item" @click="$rui.route('/pages/product/sbox-g3/finger/finger')">
					<view class="xbox_controller_item_name">
						指纹列表
					</view>
					<rui-icons icon="right" color="#ccc"></rui-icons>
				</view>
				<view class="xbox_controller_item" @click="unbind">
					<view class="xbox_controller_item_name">
						解绑设备
					</view>
					<rui-icons icon="right" color="#ccc"></rui-icons>
				</view>
				<view class="xbox_controller_item" @click="$rui.route('/pages/product/sbox-g3/ota/ota')">
					<view class="xbox_controller_item_name">
						固件升级
					</view>
					<rui-icons icon="right" color="#ccc"></rui-icons>
				</view>
				<view class="xbox_controller_item" @click="restore">
					<view class="xbox_controller_item_name">
						恢复出厂设置
					</view>
					<rui-icons icon="right" color="#ccc"></rui-icons>
				</view>
				<view class="xbox_controller_item" @click="$rui.route('/pages/user/help/help')">
					<view class="xbox_controller_item_name">
						常见问题
					</view>
					<rui-icons icon="right" color="#ccc"></rui-icons>
				</view>
			</view>

			<view class="version" v-if="info.version">
				v.1.0.{{info.version}}
			</view>
		</view>

		<rui-loading ref="refLoading" :message="loading.message"></rui-loading>
	</rui-pages>
</template>

<script setup>
	import {
		ref
	} from "vue";
	import {
		onLoad,
		onShow,
		onUnload
	} from "@dcloudio/uni-app"
	import ble from "@/util/ble.js"
	import {
		_handleBuffer,
		_sum,
		_handleElectricity,
		_chunkArray,
		createBuffer
	} from "@/util/common.js"
	import {
		getCupInfo, //更改名称为getDeviceInfo
		delFinger,
		delProduct,
		restoreFactory,
		getFingerAll,
		addFinger
	} from "@/common/api.js"

	import {
		productStore
	} from "@/store/index.js"

	let product = productStore();

	let refLoading = ref();
	let loading = ref({
		message: "请触摸指纹激活设备",
		status: false,
		error: false,
		second: 5,
	})

	let info = ref({})
	let config = {}

	const quit = (msg) => {
		refLoading.value.error(msg || "设备断开")

		console.log("退出设备首页")
		setTimeout(_ => {
			uni.switchTab({
				url: "/pages/tabbar/index/index"
			})
		}, 5000)
	}

	onShow(() => {
		ble.watch = (event, d) => {
			console.log(event, d)
			if (event == 'state2') {
				// loading.value.remainder = d.remainder;
				loading.value.message = `请触摸指纹激活设备 ${d.remainder}s`
			}
			if (event === 'state') {
				info.value.connect = d.connected;
				if (d.connected) {
					loading.value.message = "数据加载中"
				} else {
					quit(d.msg)
				}
			}
			if (event == 'notify') {
				if (d.command == "40") {
					refLoading.value.close();

					ble.ping(14);

					//电量
					info.value.quantity = _handleElectricity(d.data[3] + d.data[4])

					console.log("电量十六进制：", d.data[3] + d.data[4], "电量百分比：", info.value.quantity)

					//指纹数量
					let finger_number = parseInt(d.data[2], 16);
					product.setFingerprint(finger_number || 0)

					console.log("指纹数量", finger_number)


					//同步指纹
					syncFinger(finger_number)
					//版本号
					info.value.version = parseInt(d.data[1], 16);
					console.log('版本号', info.value.version)
					ota(info.value.version)


				}

			}

			if (event === 'start') {
				let data = (new Date().getTime() / 1000 >> 0).toString(16);
				ble.send(createBuffer(40, 4, data), '', 500)
			}
		}
	})

	onUnload(() => {
		ble.close()
		ble.watch = function() {}
		ble.error = function() {}
	})
	onLoad(opts => {
		console.log(opts)

		info.value.image = opts.image;
		info.value.color = opts.color;
		info.value.user_product_id = opts.id;
		info.value.product_id = opts.product_id;

		uni.setNavigationBarTitle({
			title: opts.name || "设备首页"
		});

		//设置蓝牙设备ID
		ble.config({
			deviceId: opts.mac,
			serviceId: "6E400001-B5A3-F393-E0A9-E50E24DC4179",
			properties(type, uuid) {
				if (type == 'write') {
					return uuid.includes("6E400002")
				}
				if (type == 'notify') {
					return uuid.includes("6E400003")
				}
			}
		})
		ble.error = (event, d) => {
			console.log(event, d)
			//设备连接失败
			// if (d.code == 10007 || event == "connection" || event === "services" || event ===
			// 	"characteristics") {
			// 	info.value.connect = false;
			// 	quit()
			// }
			if(event == 'quit') {
				info.value.connect = false;
				quit(d.msg)
			}

		}
		getCupInfo({
			id: opts.id
		}).then(res => {
			config = res.data;
			product.setInfo(res.data);
			ble.connect();
		})
	})

/**
	 * 同步指纹
	 */
	const syncFinger = (number) => {
		getFingerAll({
			user_product_id: info.value.user_product_id
		}).then(res => {
			/**
			 * 判断数据库指纹数量与设备数量是否相符
			 * 1、设备指纹数量未同步至数据库
			 * 2、查找缺失的key
			 * 3、提交设备录入的key
			 */
			let keys = res.data.keys;
			if (res.data.number >= 10) return;
			if (number > res.data.number) {
				let k = [];
				for (let key = 0; key <= number; key++) {
					if (!keys.includes(key) && key > 0) {
						//同步设备录入指纹
						console.log('------------未同步指纹', key)
						k.push(key)
					}
				}
				if (!k.length) return false;
				console.log(22222, k, info.value.user_product_id)
				addFinger({
					name: "设备指纹",
					user_product_id: info.value.user_product_id,
					keys: k.join(',')
				}).then(res => {
					console.log(2222222)
				})
			}
		})
	}
	
	//蓝牙解锁水杯
	const open = () => {
		uni.showLoading({
			title: '开锁中',
			mask: true,
		});
		setTimeout(() => {
			uni.hideLoading();
		}, 1000)
		ble.send(createBuffer(10))
	}

	const restore = () => {
		uni.showModal({
			title: '警告提示',
			content: '您是否要清除设备上所有数据？',
			success: function(res) {
				if (res.confirm) {
					ble.send(createBuffer(21), () => {
						uni.showToast({
							title: "初始成功",
							icon: "success"
						})
						
						//删除指纹, 删除喝水次数
						restoreFactory({
							user_product_id: info.value.user_product_id
						})
						setTimeout(() => {
							uni.switchTab({
								url: "/pages/tabbar/index/index"
							})
						}, 1500)
					})


				}
			}
		});
	}

	const unbind = () => {
		uni.showModal({
			title: '警告提示',
			content: '您是否将此设备从小程序移除？',
			success: function(res) {
				if (res.confirm) {
					ble.send(createBuffer(21))
					//删除指纹, 删除喝水次数
					
					restoreFactory({
						user_product_id: info.value.user_product_id
					}).then(() => {
						
						delProduct({
							id: info.value.user_product_id
						}).then(res => {
							uni.showToast({
								title: "移除成功",
								icon: "success"
							})
							setTimeout(() => {
								ble.close()
								uni.switchTab({
									url: "/pages/tabbar/index/index"
								})
							}, 1500)
						})
					})

				}
			}
		});
	}

	const ota = (ver) => {
		product.setVersion(ver)
		product.setUpdate(false)
		// 对比版本是否升级。
		if (config.version.v > ver) {
			product.setUpdate(true)
			if (config.version.grade == 0) {
				_toOta()
			} else if (config.version.grade == 1) {
				setTimeout(_ => {
					uni.showModal({
						title: "升级提示",
						content: "发现新版本是否升级？",
						success(res) {
							if (res.confirm) _toOta()
						}
					})
				}, 1000)
			}
		}

		function _toOta() {
			uni.redirectTo({
				url: "/pages/product/sbox-g3/ota/ota"
			});
		}
	}
</script>

<style lang="scss" scoped>
	.version {
		text-align: center;
		padding: 15rpx 0;
		color: #ddd;
	}
	.xbox {
		&_controller {
			margin-top: 50rpx;

			&_item {
				display: flex;
				justify-content: space-between;
				background: #fff;
				margin: 20rpx;
				padding: 0 30rpx;
				height: 120rpx;
				border-radius: 20rpx;
				line-height: 120rpx;
			}
		}

		&_fast {
			display: flex;
			flex-wrap: wrap;
			margin: 60rpx 0 30rpx;

			&_item {
				width: 50%;
				text-align: center;
				display: flex;
				justify-content: center;

				&_box {
					text-align: center;
					display: flex;
					justify-content: center;
					background: #fff;
					width: calc(100% - 40rpx);
					text-align: center;
					height: 140rpx;
					border-radius: 20rpx;
					line-height: 140rpx;
					// box-shadow: 0 3rpx 10rpx rgba(0, 0, 0, .03);

					&:active {
						background: #ddd;
					}

					&_name {
						margin-left: 10rpx;
						font-size: 32rpx;
						font-weight: bold;
					}
				}
			}
		}

		&_head {
			border-bottom-left-radius: 50rpx;
			border-bottom-right-radius: 50rpx;
			background: #fff;
			// box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, .1);
			text-align: center;
			padding: 30rpx;
			position: relative;

			&_info {

				// width: 80rpx;
				background: #eee;
				padding: 20rpx;
				border-radius: 20rpx;
				display: flex;
				margin-top: 50rpx;

				&_item {
					background: #fff;
					padding: 10rpx 0 5rpx;
					margin-right: 20rpx;
					border-radius: 20rpx;
					width: 50%;

					&:last-child {
						margin-right: 0;
					}

					&_text {
						font-size: 24rpx;
						color: #999;
					}

					&_value {
						font-size: 38rpx;
						font-weight: bold;
					}
				}
			}

			&_img {
				height: 100%;

			}
		}
	}
</style>